﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="FocusActiveAwareAdapter.cs" company="Concept Architecture">
//   (c) 2010 Muhammad Umer Farooq
// </copyright>
// <summary>
//   Defines the FocusActiveAwareAdapter type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Hisaab.Windows.Common
{
    using System;
    using System.Windows;

    /// <summary>
    /// Defines the <seealso cref="FocusActiveAwareAdapter"/> type.
    /// </summary>
    public class FocusActiveAwareAdapter : IActiveAware
    {
        /// <summary>
        /// Is active flag
        /// </summary>
        private bool _isActive;

        /// <summary>
        /// Initializes a new instance of the <see cref="FocusActiveAwareAdapter"/> class.
        /// </summary>
        /// <param name="frameworkElement">The framework element.</param>
        public FocusActiveAwareAdapter(FrameworkElement frameworkElement)
        {
            frameworkElement.GotFocus += delegate
            {
                IsActive = true;
            };

            frameworkElement.LostFocus += delegate
            {
                IsActive = false;
            };

            // loaded and unloaded can occur multiple times in the life cycle of a WPF element
            frameworkElement.Loaded += delegate
            {
                IsActive = true;
            };

            frameworkElement.Unloaded += delegate
            {
                IsActive = false;
            };
        }

        /// <summary>
        /// Occurs whenever the <see cref="IsActive"/> property has changed.
        /// </summary>
        public event EventHandler<EventArgs> IsActiveChanged;

        /// <summary>
        /// Gets a value indicating whether this object is active.
        /// </summary>
        public bool IsActive
        {
            get
            {
                return _isActive;
            }

            private set
            {
                if (_isActive != value)
                {
                    _isActive = value;
                    if (IsActiveChanged != null)
                    {
                        IsActiveChanged.DynamicInvoke(this, EventArgs.Empty);
                    }
                }
            }
        }
    }
}